import React from 'react';
import {inject, observer} from 'mobx-react';
import { withRouter, Route } from 'react-router-dom';
import { catchApiError } from '../../util/index';
import { Icon, Tools, PhotoSwipe, FilePicker,Button,WhiteSpace } from 'weaver-mobile';
import { Comment, Reply, MapPage } from 'weaver-mobile-page';
import QueueAnim from 'rc-queue-anim';
import { Base64 } from 'js-base64';
import WeaUtils from '../../public/wea-utils';
import BlogWrite from './BlogWrite';
import ShowCheckUserList from './ShowCheckUserList';

const getLabel = Tools.getLabel;

@withRouter
@inject('blogCommentStore')
@observer
export default class BlogComment extends React.Component {
  static defaultProps = {
    prefixCls: 'blog-comment'
  }

  constructor(props) {
    super(props);
    let funcs = ['getBlogInfo'];
    funcs.forEach((func) => this[func] = this[func].bind(this));
    this.state = {
      files: [],
      multiple: false,
      showImage: false,
      index: 0,
      lat: null,
      lnt: null, 
      title: null,
      test:'申请关注',
      blogInfo: undefined,
      indexBlog: undefined,
      isNull:true
    }
    this.replyRef=React.createRef();
  }

  componentDidMount() {
    const { replyStore, storeName } = this.props;
    replyStore[storeName].setToWriteBlog(this.toWriteBlog);
    replyStore[storeName].setReplyVisible(this.setReplyVisible);
    this.photoSwipePreview();
    //this.getBlogInfo();
    // console.log('BlogComment-------componentDidMount----');
  }

  getBlogInfo() {
		this.getBlogInfoByUserId(this.props.userInfo.id);
	}

  getBlogInfoByUserId(userId) {
		if (!userId) return;


  const options = {
      url: '/api/blog/base/getBlogPersonalInfo',
      method: 'GET',
      params: { blogId: userId  },
      type: 'json',
    };
    return Tools.callApi(options).then(catchApiError);
  //  Tools.callApi(options).then((result) => {
  //     this.setState({ blogInfo: result });
	//     if (result.viewStatus > 0) {
  //        const params = {
  //        url: '/api/blog/base/getBlogWorkIndex',
  //        method: 'GET',
  //        params: { blogId: userId  },
  //        type: 'json',
  //       };
  //        Tools.callApi(params).then((result) => {
	//         this.setState({ indexBlog: result })
  //        })
  //     }
  //   });
	}

  componentDidUpdate(){
    // console.log('BlogComment-------componentDidUpdate----');
    this.photoSwipePreview();
  }

  componentWillUnmount() {
    const { replyStore, storeName } = this.props;
    replyStore[storeName].clearComment();
  }

  photoSwipePreview = () => {
    setTimeout(() => {
      let msgArr = document.getElementsByClassName("wm-comment-content-msg");
      let imgArr = [];
      let imgArrTemp = [];
      for(let i=0; i<msgArr.length; i++){
        imgArrTemp = msgArr[i].getElementsByTagName("img"); 
        for(let j=0; j<imgArrTemp.length; j++){
          imgArr.push(imgArrTemp[j]);
        }
      }

      this.state.files = [];
      for(let k=0; k<imgArr.length; k++){
        this.state.files.push({url: imgArr[k].src});
        imgArr[k].onclick = () => {this.onItemClick(k)};
      }
    }, 800);
  }

  toWriteBlog = () => {
    const { path, id, history } = this.props;
    history.push(`${path}/${id}`);
  }

  setReplyVisible = (val) => {
    const replyRef = this.replyRef;
    if (replyRef) {
      replyRef.setState({ visible: !replyRef.state.visible }, () => {
        replyRef.getInputFocus();
      });
    } else {
      window.setTimeout(()=>{
        this.setReplyVisible();
      },0)
    }
  }

  getDay = (num, str) => { 
    let today = new Date(); 
    let nowTime = today.getTime(); 
    let ms = 24*3600*1000*num; 
    today.setTime(parseInt(nowTime + ms)); 
    let oYear = today.getFullYear(); 
    let oMoth = (today.getMonth() + 1).toString(); 
    if (oMoth.length <= 1) oMoth = '0' + oMoth; 
    let oDay = today.getDate().toString(); 
    if (oDay.length <= 1) oDay = '0' + oDay; 
    return oYear + str + oMoth + str + oDay; 
  }

  renderRightTop = (data) => {
    // if(data.isPermissions==0){
    //   return '';
    // }
    const { prefixCls } = this.props;
    let { workdate, isReaded } = data;
    let _dateF1 = WeaUtils.DateFormat(workdate,'M月dd日').replace('月',getLabel(33452,'月')).replace('日',getLabel(390,'日'));
    let _weekF1 = WeaUtils.DateFormat(workdate,'周E').replace('周日',getLabel(398,'星期日')).replace('周一',getLabel(392,'星期一')).replace('周二',getLabel(393,'星期二'))
    .replace('周三',getLabel(394,'星期三')).replace('周四',getLabel(395,'星期四')).replace('周五',getLabel(396,'星期五')).replace('周六',getLabel(397,'星期六'));
   
   return <div> 
      <div className={`${prefixCls}-right-top`} title={isReaded}>
      {(WeaUtils.DateFormat(new Date(), 'yyyy-MM-dd') === workdate) ? 
          <span>{_dateF1}&nbsp;&nbsp;{getLabel(15537,'今天')}</span> : 
          this.getDay(-1, '-') === workdate ?
          <span>{_dateF1}&nbsp;&nbsp;{getLabel(82640,'昨天')}</span> :
          <span>{_dateF1}&nbsp;&nbsp;{_weekF1}</span>}
      </div>
      {isReaded === 0 ?
        <div className={`${prefixCls}-right-top-unread`}><Icon type='blog-new' size='md' color='red'/></div>:""
      }
      </div>
  }

  renderTopContent = (data) => {
    const { prefixCls } = this.props;
    if (data.content === '') {
      return (
        <div className={`${prefixCls}-content-unSubmit`}>
          <Icon type='warning' size='xs'/>
          <span>{getLabel(384397,'未提交微博')}</span>
        </div>
      )
    } else if(data.replenish) {
      return (
        <div className={`${prefixCls}-content-supplement`}>
          <Icon type='blog-bujiao' size='xxs'/>
          <span>{data.replenishSpan}</span>
        </div>
      )
    }
  }

  onItemClick = (index) => {
    this.setState({
      showImage: true,
      index: index
    });
    PhotoSwipe.showImage(this.state.files, index);
  }

  showPosition = (data) => {
    const { position: { lat, lnt, title } } = data;
    this.setState({ lat, lnt, title },()=>{
      this.props.history.push(`${this.props.path}/map`);
    });
  }



   gotoCheckUserList = (e,discussid) => {

       if (e.preventDefault) e.preventDefault();
       e.stopPropagation();
       let pname = `${this.props.path}/showCheckUserList`;
       this.props.history.push({pathname:pname,query:{discussid:discussid}});


  }

    customShowName = (data) => {




      if(data.appItems.length>0&&data.appItems[0]&&data.appItems[0].itemName){
          let ishappy = data.appItems[0].itemName=='26917'?"blog-gaoxing":"blog-bugaoxing";


          let happyStyle = { "position": "absolute", "width": "17px", "margin-left":"23px","color": "#8c959c", "margin-top": "-1px"};


          if(this.props.storeName=='hisBlog'||data.specialStatus==0){
              happyStyle ={ "position": "absolute", "width": "17px", "margin-left":"4px","color": "#8c959c", "margin-top": "-1px"};
          }

          if(data.specialStatus!=0&&data.appItems[0].faceImg==''){
              return <span>
            {data.name}
                  {this.props.storeName=='hisBlog'||data.specialStatus==0?"": <Icon type="special-concern-1"  style={{ "position": "absolute", "width": "17px", "margin-left":" 4px", "margin-top": "-1px", "color": "#ffc600"}} />}
            </span>
          }

          if(data.specialStatus==0&&data.appItems[0].faceImg!=''){
              return <span>
            {data.name}
                  {data.appItems[0].faceImg!=''? <Icon type={ishappy}  style={{ "position": "absolute", "width": "17px", "margin-left":" 4px","color": "#8c959c", "margin-top": "-1px"}} />:""}
                  {data.shareType==2? <Icon type="sirenzu"  style={{ "position": "absolute", "width": "17px", "margin-left":"26px", "margin-top": "-1px", "color": "#3d80b4"}} />:""}
                  {data.shareType==3||data.shareType==4? <Icon type="linked-account"  style={{ "position": "absolute", "width": "17px", "margin-left":"26px", "margin-top": "-1px", "color": "#3d80b4"}} onClick={(e) => this.gotoCheckUserList(e,data.discussid)} />:""}
            </span>
          }

          if(data.specialStatus==0&&data.appItems[0].faceImg==''){
              return <span>
            {data.name}
                  {data.shareType==2? <Icon type="sirenzu"  style={{ "position": "absolute", "width": "17px", "margin-left":" 4px", "margin-top": "-1px", "color": "#3d80b4"}} />:""}
                  {data.shareType==3||data.shareType==4? <Icon type="linked-account"  style={{ "position": "absolute", "width": "17px", "margin-left":" 4px", "margin-top": "-1px", "color": "#3d80b4"}} onClick={(e) => this.gotoCheckUserList(e,data.discussid)}/>:""}
            </span>
          }


          if(data.specialStatus!=0&&data.appItems[0].faceImg!=''){
              return <span>
                   {data.name}
                  {this.props.storeName=='hisBlog'||data.specialStatus==0?"": <Icon type="special-concern-1"  style={{ "position": "absolute", "width": "17px", "margin-left":" 4px", "margin-top": "-1px", "color": "#ffc600"}} />}
                  {data.appItems[0].faceImg!=''? <Icon type={ishappy}  style={happyStyle} />:""}

              </span>
          }
      }else{
          if(data.specialStatus==0||this.props.storeName=='hisBlog'){
              return <span>
            {data.name}
                  {data.shareType==2? <Icon type="sirenzu"  style={{ "position": "absolute", "width": "17px", "margin-left":" 4px", "margin-top": "-1px", "color": "#3d80b4"}} />:""}
                  {data.shareType==3||data.shareType==4? <Icon type="linked-account"  style={{ "position": "absolute", "width": "17px", "margin-left":" 4px", "margin-top": "-1px", "color": "#3d80b4"}} onClick={ (e) => this.gotoCheckUserList(e,data.discussid)}/>:""}
              </span>
          }else{
              return <span>
            {data.name}
                  {data.specialStatus==0?"": <Icon type="special-concern-1"  style={{ "position": "absolute", "width": "17px", "margin-left":" 4px", "margin-top": "-1px", "color": "#ffc600"}} />}
            </span>
          }
      }
    }



    render() {
    /* 
      1、commentType: 样式中是否显示日期标识
      2、storeName: 指向不同的new BlogCommentStore
    */
    const { commentType, storeName, replyStore, path, id, hasInitialListSize, prefixCls, avatarClick,replyClassName } = this.props;
    let { blogCommentStore, saveComment, replyComment, commentReplyStoreMap, reply } = replyStore[storeName];
    const { lat, lnt, title } = this.state;
    if (replyComment) {
      reply = commentReplyStoreMap[replyComment.replyId];
    }

    const leftConfig = [
      { type: 'voice' },
      { type: 'blog-tupian' },
      { type: 'blog-biaoqing' },blogCommentStore
      //  { type: '@' },
    ];
    const rightConfig = { type: 'private', text: getLabel(83281,'私密') };

    return (
      <div className={prefixCls+" "+replyClassName}>
        <Comment
          store={blogCommentStore}
          hasInitialListSize={hasInitialListSize || false}
          renderRightTop={commentType ? '' : data => this.renderRightTop(data)}
          customShowName={ this.customShowName}
          renderTopContent={this.renderTopContent}
          onAvatarClick={(data) => avatarClick && avatarClick(data)}
          showPosition={this.showPosition}
        />
        {
          reply && <Reply
          // ref={ref => this.replyRef = ref}
          wrappedComponentRef={ref => this.replyRef = ref}
          store={reply}
          leftConfig={leftConfig}
          rightConfig={rightConfig}
          placeholder={getLabel(18546,'回复内容...')}
          visible={false}
          onSubmit={(datas) => saveComment(datas,() =>{
            this.photoSwipePreview();
          } )}
        />
        }
        <Route 
          key={id}
          path={`${path}/${id}`}
          breadcrumbName="编辑评论"
          render={() => (
            <div className="wm-route-layout" style={{ position: 'fixed' }}>
              <QueueAnim>
                <BlogWrite key="write" writeBlogStore={replyStore[storeName]} storeName={this.props.storeName} />
              </QueueAnim>
            </div>
          )}
        />
        <div style={{display: 'none'}}>
          <FilePicker
            listType='img'
            files={this.state.files}
          />
        </div>
        <Route 
          key='map'
          path={`${path}/map`}
          breadcrumbName="地图"
          render={() => (
            <div className="wm-route-layout" style={{ position: 'fixed' }}>
              <QueueAnim>
                <MapPage
                  store={blogCommentStore.mapPage}
                  position={[lat, lnt]}
                  address={title}
                />
              </QueueAnim>
            </div>
          )}
        />

          <Route
              key='checkUserList'
              path={`${path}/showCheckUserList`}
              breadcrumbName="公开范围人员"
              render={() => (
                  <div className="wm-route-layout" style={{ position: 'fixed' }}>
                      <QueueAnim>
                          <ShowCheckUserList  userList={[]} shareType="3"/>
                      </QueueAnim>
                  </div>
              )}
          />

      </div>
    )
  }
}